package com.anlogic.sdk.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ProcLauncherUtils {
	private static final IProcLauncher launcher = UtilsPlugin.getDefault().getProcLauncher();

	private static final String KILL_SERVER_CMD = "kill_server %s";

	private static final String AARCH32_INIT_CMD = "aarch32_init %s %s %s";

	private static final String AARCH32_ENTRY_ADDRESS_CMD = "aarch32_entry_address %s";

	private static final String TEST_CONNECTION_CMD = "test_connection %s %s";

	private static final String SCAN_USB_CMD = "scan_usb %s %s";

	private static final String KILL_EXECUTE_CMD = "kill_execute %s";
	
	private static final String RELEASE_LOCKDOWN = "release_lockdown";
	
	private static final String CHECK_HWSERVER = "check_hwserver";
	
	private static final String CHECK_USBDRIVER = "check_usbdriver";

	public static String runCmd(String cmd) {
		return launcher.launch(cmd);
	}
	
	public static void killServer(String port) {
		launcher.launch(String.format(KILL_SERVER_CMD, port));
	}

	public static void initializeAArch32(String ip, String port, String bsp_loc) {
		launcher.launch(String.format(AARCH32_INIT_CMD, ip, port, bsp_loc));
	}

	public static String getAArch32EntryAddress(String imageFile) {
		return launcher.launch(String.format(AARCH32_ENTRY_ADDRESS_CMD, imageFile));
	}

	public static String testConnection(String host, String port) {
		return launcher.launch(String.format(TEST_CONNECTION_CMD, host, port));
	}

	public static String scanUsb(String vid, String pid) {
		return launcher.launch(String.format(SCAN_USB_CMD, vid, pid));
	}

	public static String killExecute(String exe) {
		return launcher.launch(String.format(KILL_EXECUTE_CMD, exe));
	}
	
	public static String releaseLockdown() {
		return launcher.launch(RELEASE_LOCKDOWN);
	}
	
	public static String getHwserverInfo() {
		String ret = launcher.launch(CHECK_HWSERVER);
		String regex = "\\b(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}):(\\d{1,5})\\b";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(ret);
        if (matcher.find()) {
        	String host = matcher.group(1);
        	String port = matcher.group(2);
        	return String.format("%s:%s", host, port);
        }
		return null;
	}
	
	public static boolean isHwserverRunning() {
		String info = getHwserverInfo();
		if (info != null) {
			return true;
		}
		return false;
	}
	
	public static String getUsbDriver() {
		String ret = launcher.launch(CHECK_USBDRIVER);
		String regex = "Driver\\s*:\\s*(\\w+)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(ret);
        if (matcher.find()) {
        	String driver = matcher.group(1);
        	return driver;
        }
		return null;
	}
	
	public static boolean isWinUsbDriver() {
		String driver = getUsbDriver();
		if (driver != null && driver.equalsIgnoreCase("WINUSB")) {
			return true;
		}
		return false;
	}
}
